package com.xafc.demo.sys.service.impl;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.base.CaseFormat;
import com.xafc.demo.sys.dao.UserMapper;
import com.xafc.demo.sys.model.dto.MenuDto;
import com.xafc.demo.sys.model.dto.RoleDto;
import com.xafc.demo.sys.model.dto.UserDto;
import com.xafc.demo.sys.model.entity.User;
import com.xafc.demo.framework.result.ResultCode;
import com.xafc.demo.sys.model.query.UserPageQuery;
import com.xafc.demo.sys.service.IUserService;
import com.xafc.demo.framework.utils.CommonUtils;
import com.xafc.demo.framework.utils.UnixDateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private UserMapper userMapper;

    /**
    @Override
    public Page<User> getUserList(UserPageQuery query) {
        // 设置分页
        final Page<User> page = new Page<>(query.getPage(), query.getLimit());
        // 设置排序
        if(StrUtil.isNotEmpty(query.getOrder())){
            // 驼峰转换
            String field = CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, query.getField());
            String order = query.getOrder();
            page.setOrders(
                ListUtil.toList(
                    StrUtil.equals("asc", order) ? OrderItem.asc(field) : OrderItem.desc(field)
                ));
        }else {
            // 默认排序
            page.setOrders(ListUtil.toList(OrderItem.desc("id")));
        }

        // 设置搜索
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq(query.getDept()!=null && query.getDept() > 0, "dept", query.getDept())
               .eq(query.getStatus()!=null, "status", query.getStatus())
               .and(StrUtil.isNotEmpty(query.getSearch()),
                    i -> i.like("name", query.getSearch())
                          .or()
                          .like("username", query.getSearch())
               );

        return baseMapper.selectPage(page, wrapper);
    }
    */


    @Override
    public Page<UserDto> getUserListByWrapper(UserPageQuery query) {
        // 设置分页
        final Page<UserDto> page = new Page<>(query.getPage(), query.getLimit());
        // 设置排序
        if(StrUtil.isNotEmpty(query.getOrder())){
            // 驼峰转换
            String field = CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, query.getField());
            String order = query.getOrder();
            page.setOrders(
                    ListUtil.toList(
                            StrUtil.equals("asc", order) ? OrderItem.asc(field) : OrderItem.desc(field)
                    ));
        }else {
            // 默认排序
            page.setOrders(ListUtil.toList(OrderItem.desc("id")));
        }
        // 设置搜索
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq(query.getDept()!=null && query.getDept() > 0, "u.dept", query.getDept())
                .eq(query.getStatus()!=null, "u.status", query.getStatus())
                .and(StrUtil.isNotEmpty(query.getSearch()),
                        i -> i.like("u.name", query.getSearch())
                                .or()
                                .like("u.username", query.getSearch())
                );


        List<UserDto> userDtoList = baseMapper.selectUserListByWrapper(page, wrapper);
        page.setRecords(userDtoList);
        return page;
    }


    @Override
    public Page<UserDto> getUserList(UserPageQuery query) {
        // 设置分页
        final Page<UserDto> page = new Page<>(query.getPage(), query.getLimit());
        // 设置排序
        if(StrUtil.isNotEmpty(query.getOrder())){
            // 驼峰转换
            String field = CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, query.getField());
            String order = query.getOrder();
            page.setOrders(
                    ListUtil.toList(
                            StrUtil.equals("asc", order) ? OrderItem.asc(field) : OrderItem.desc(field)
                    ));
        }else {
            // 默认排序
            page.setOrders(ListUtil.toList(OrderItem.desc("id")));
        }

        List<UserDto> userDtoList = baseMapper.selectUserList(page, query);
        page.setRecords(userDtoList);
        return page;
    }

    @Override
    public User getUserById(Integer id) {
        return baseMapper.selectById(id);
    }

    @Override
    public User getUserByUsername(String username) {
        return baseMapper.selectUserByUsername(username);
    }

    @Override
    public List<User> getUserByIds(List<Integer> ids) {
//        return baseMapper.selectBatchIds(ids);
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.select("id", "name").in("id", ids);
        return baseMapper.selectList(wrapper);
    }

    @Override
    public ResultCode addUser(User user) {
        ResultCode resultCode;
        Integer count = baseMapper.selectCount(new QueryWrapper<User>().eq("username", user.getUsername()));
        //用户名已存在
        if (count > 0){
            resultCode = ResultCode.fail("用户名已存在");
        }else {
            final String randomStr = RandomUtil.randomString(8);
            final String md5password = SecureUtil.md5(SecureUtil.md5("123456") + randomStr);
            final int nowUnix = UnixDateUtil.unixTime();
            final String lastIp = CommonUtils.getIpAddrByRequestHolder();
            user.setSalt(randomStr);
            user.setPassword(md5password);
            user.setCreateTime(nowUnix);
            user.setLastIp(lastIp);

            int num= baseMapper.insert(user);
            //新增成功
            if (num>0){
                resultCode = ResultCode.success("新增成功");
            }else {
                resultCode = ResultCode.error( "新增失败");
            }
        }
        return resultCode;
    }

    @Override
    public ResultCode updateUser(User user) {
        ResultCode resultCode;
        Integer count = baseMapper.selectCount(new QueryWrapper<User>().eq("id", user.getId()));
        if(count > 0){
            int num = baseMapper.updateById(user);
            if(num>0){
                resultCode = ResultCode.success("更新成功");
            }else {
                resultCode = ResultCode.error("更新失败");
            }
        }else {
            resultCode = ResultCode.fail("无效的用户");
        }
        return resultCode;
    }

    @Override
    public ResultCode deleteUser(Integer id) {
        ResultCode resultCode;
        Integer count = baseMapper.selectCount(new QueryWrapper<User>().eq("id", id));
        if(count > 0){
            int num = baseMapper.deleteById(id);
            if(num>0){
                resultCode = ResultCode.success("删除成功");
            }else {
                resultCode = ResultCode.error("删除失败");
            }
        }else {
            resultCode = ResultCode.fail("无效的用户");
        }
        return resultCode;
    }

    @Override
    public List<RoleDto> getUserRole(Integer id) {
        return baseMapper.selectUserRoles(id);
    }

    @Override
    public List<MenuDto> getUserPerm(Integer id) {
        return baseMapper.selectUserPerms(id).stream().distinct().collect(Collectors.toList());
    }

}
